<?php
/**
 * 是否授权
 * @return array $userData; 返回用户资料
 */
function is_oauth($options){
	$_SESSION=NULL;
	$auth = new \Common\Api\WeixinAuth($options);
	//$auth = new wxauth($options); //授权
	if ($auth){
		$userData = $auth->wxuser;
		if ($userData) save_oauth_user($options,'snsapi_userinfo', $userData);
		return $userData;
	}
} 
/**
 * 保存用户资料
 * @param string $scope 类型
 * @param array $userdata 用户资料
 * @return int $uid; 返回UID
 */
function save_oauth_user($options, $scope='snsapi_base', $userdata){
	global $db;
	$prefix = $options['DB_PREFIX'];
	
	if (!$userdata) return false;

	require_once(APP_PATH . '/Common/Common/emoji.php');

	$db = M('weixin_member');
	$map['openid'] = $userdata['open_id'];
	$rs = $db->where($map)->field('id,nickname')->find();

	$nickname = emoji_unified_to_html($userdata['nickname']);
	if (!$nickname) $nickname = $userdata['nickname'];
	if ($scope=='snsapi_base'){
		$record = array(
			"openid"=>$userdata['open_id'],
			'scope'=>'snsapi_base',
			'ip'=>get_client_ip(),
			'update_time'=>time()
		);
	}else{
		$record = array(
			"openid"=>$userdata['open_id'],
			'nickname'=>$nickname,
			'sex'=>$userdata['sex'],
			'province'=>$userdata['province'],
			'city'=>$userdata['city'],
			'country'=>$userdata['country'],
			'headimgurl'=>$userdata['avatar'],
			'scope'=>'snsapi_userinfo',
			'ip'=>get_client_ip(),
			'update_time'=>time()
		);
	}

	if (!$rs){ //save
		$uid = $db->add($record);

	}else{ //update
		$db->where($map)->save($record);
		$uid = $rs['id'];
	}

	$user = array(
        'uid' => $uid,
        'nickname' => $nickname,
        'last_login_time' => time(),
    );
    session('user_auth', $user);
    session('user_auth_sign', data_auth_sign($user));

	//unset($_SESSION[$options['APP_NAME']]);
	/*$_SESSION[$options['APP_NAME']] = array(
		'uid'=>$uid,
		'nickname'=>$rs['nickname'],
		'oauthtime'=>time()
	);*/
	
	// p($_SESSION); exit;
	// p(session('user_auth')); exit;
	return $uid;
}
?>